package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.ByteUtil;
import com.firefightingiot.firefightingiot.model.DeviceBusiness;
import com.firefightingiot.firefightingiot.model.DeviceSwitch;
import com.firefightingiot.firefightingiot.model.MaintenanceDevice;
import com.firefightingiot.firefightingiot.model.UltrasonicDevice;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.DeviceBusinessMapper;
import com.firefightingiot.firefightingiot.web.mapper.DeviceSwitchMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: YangYu
 * @ClassName: DeviceSwitchService
 * @Date: Created in 9:17 2023/2/20
 * @Description: 设备开关量服务
 */
@Service
public class DeviceSwitchService extends BaseService {

    @Resource
    private DeviceSwitchMapper deviceSwitchMapper;
    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    /**
     * @Author YangYu
     * @Description 开关列表
     * @Date Created in 9:19 2023/2/20
     * @Param [jsonParam]
     */

    public RespEntity deviceSwitchList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        if (StrUtil.isBlank(jsonParam.getStr("transDeviceCode"))){
            return RespEntity.fail("transDeviceCode不能为空!");
        }
        List<DeviceSwitch> deviceSwitchList = deviceSwitchMapper.selectList(new QueryWrapper<DeviceSwitch>().eq("trans_device_code",jsonParam.getStr("transDeviceCode")));
        return RespEntity.success(deviceSwitchList);
    }

    /**
     * @Author YangYu
     * @Description 开关新增、编辑
     * @Date Created in 9:26 2023/2/20
     * @Param [jsonParam]
     */

    public RespEntity deviceSwitchAddOrUpdate(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        DeviceSwitch deviceSwitch = new DeviceSwitch();
        if (jsonParam.containsKey("id")){
            deviceSwitch.setId(jsonParam.getStr("id"));
            deviceSwitch.setName(jsonParam.getStr("name"));
            deviceSwitch.setNumber(jsonParam.getStr("number"));
            deviceSwitch.setInstalltime(jsonParam.getStr("installTime"));
            deviceSwitch.setPosition(jsonParam.getStr("position"));
            deviceSwitch.setTransDeviceCode(jsonParam.getStr("transDeviceCode"));
            deviceSwitch.setCurrentstate("2");
            deviceSwitchMapper.deleteById(jsonParam.getStr("id"));
        }else {
            deviceSwitch.setId(UUID.randomUUID().toString());
            deviceSwitch.setName(jsonParam.getStr("name"));
            deviceSwitch.setNumber(jsonParam.getStr("number"));
            deviceSwitch.setInstalltime(jsonParam.getStr("installTime"));
            deviceSwitch.setPosition(jsonParam.getStr("position"));
            deviceSwitch.setTransDeviceCode(jsonParam.getStr("transDeviceCode"));
            deviceSwitch.setCurrentstate("2");
        }
        deviceSwitchMapper.insert(deviceSwitch);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 开关删除
     * @Date Created in 9:34 2023/2/20
     * @Param [jsonParam]
     */

    public RespEntity deviceSwitchDel(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("id不能为空!");
        }
        deviceSwitchMapper.deleteById(jsonParam.getStr("id"));
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 开关详情
     * @Date Created in 9:19 2023/2/20
     * @Param [jsonParam]
     */

    public RespEntity deviceSwitchDetail(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("id不能为空!");
        }
        DeviceSwitch deviceSwitch = deviceSwitchMapper.selectById(jsonParam.getStr("id"));
        return RespEntity.success(deviceSwitch);
    }
    /**
     * @Author YangYu
     * @Description 更新传输编码
     * @Date Created in 9:19 2023/2/20
     * @Param [jsonParam]
     */

    public RespEntity updateTransDeviceCode(JSONObject jsonParam) {
        deviceSwitchMapper.updateTransDeviceCode(jsonParam);
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 开关状态更新
     * @Date Created in 9:19 2023/2/20
     * @Param [jsonParam]
     */

    public RespEntity deviceSwitchStateUpdate(JSONObject jsonParam) {

        //原始数据 86445206568203905020100a0b8
        String code = jsonParam.getStr("code");
        //传输装置编码
        String transDeviceCode = code.substring(0,15);
        //寄存器值(转为二进制)
        String codeValue = ByteUtil.hexToBinaryString(code.substring(20,22));
        //batchUpdate
        //批量更新数据
        List<Map<String,Object>> list = batchUpdateData(codeValue,transDeviceCode);
        deviceSwitchMapper.batchUpdate(list);
        return RespEntity.success();
    }
    public static List<Map<String,Object>> batchUpdateData(String codeValue,String transDeviceCode){
        //batchUpdate
        //批量更新数据
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if (codeValue.charAt(7) == '1'){
            map = new HashMap<>();
            map.put("number","1");
            map.put("currentstate","2");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }else {
            map = new HashMap<>();
            map.put("number","1");
            map.put("currentstate","1");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }

        if (codeValue.charAt(6) == '1'){
            map = new HashMap<>();
            map.put("number","2");
            map.put("currentstate","2");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }else {
            map = new HashMap<>();
            map.put("number","2");
            map.put("currentstate","1");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }
        if (codeValue.charAt(5) == '1'){
            map = new HashMap<>();
            map.put("number","3");
            map.put("currentstate","2");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }else {
            map = new HashMap<>();
            map.put("number","3");
            map.put("currentstate","1");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }
        if (codeValue.charAt(4) == '1'){
            map = new HashMap<>();
            map.put("number","4");
            map.put("currentstate","2");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }else {
            map = new HashMap<>();
            map.put("number","4");
            map.put("currentstate","1");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }
        if (codeValue.charAt(3) == '1'){
            map = new HashMap<>();
            map.put("number","5");
            map.put("currentstate","2");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }else {
            map = new HashMap<>();
            map.put("number","5");
            map.put("currentstate","1");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }
        if (codeValue.charAt(2) == '1'){
            map = new HashMap<>();
            map.put("number","6");
            map.put("currentstate","2");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }else {
            map = new HashMap<>();
            map.put("number","6");
            map.put("currentstate","1");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }
        if (codeValue.charAt(1) == '1'){
            map = new HashMap<>();
            map.put("number","7");
            map.put("currentstate","2");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }else {
            map = new HashMap<>();
            map.put("number","7");
            map.put("currentstate","1");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }
        if (codeValue.charAt(0) == '1'){
            map = new HashMap<>();
            map.put("number","8");
            map.put("currentstate","2");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }else {
            map = new HashMap<>();
            map.put("number","8");
            map.put("currentstate","1");
            map.put("transDeviceCode",transDeviceCode);
            list.add(map);
        }
        return list;
    }
    /**
     * @Author YangYu
     * @Description 定时用命令获取开关状态(每10分钟执行一次)
     * @Date Created in 10:46 2022/10/9
     */
    //@Scheduled(cron="*/10 * * * * ?")
    public void getSwitchState() {

        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("device_classify", "19").eq("product_id", "10001"));

        for (DeviceBusiness deviceBusiness : deviceBusinessList) {
            JSONObject data = new JSONObject();
            data.put("number", deviceBusiness.getNumber());
            //组装下发指令
            data.put("code", "0502000000087848");
            System.out.println("开始执行");
            //下发指令
            rest(data, "switchTcp", "tcpClient", "tcp", "POST");
            System.out.println("执行结束");
        }
    }
}
